package com.yinhai.asynctask;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import com.yinhai.cfg.LoginConfig;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.constant.Contact;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.OnlineContactDetail;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.BufferException;
import com.yinhai.util.Util;

public class ContactDownloadTask extends
		AsyncTask<List<String>, Integer, Integer> {

	public static final int DOWNLOAD_ERROR = 3;
	public static final int DOWNLOAD_COMPLETED = 4;
	public static final int DOWNLOAD_CANCELED = 5;
	public static final int UN_AUTHORIZE = 6;
	public int insertSize = 0;

	private ProgressDialog downloadProgressDialog;
	private android.os.Handler handler;
	private Context context;
	public boolean flag = false;//表示从网路加载数据

	public ContactDownloadTask(Context context,
			ProgressDialog downloadProgressDialog, android.os.Handler handler) {
		this.context = context;
		this.downloadProgressDialog = downloadProgressDialog;
		this.handler = handler;
	}

	@Override
	protected void onProgressUpdate(Integer... progress) {
		// 这个函数在doInBackground调用publishProgress时触发，虽然调用时只有一个参数
		// 但是这里取到的是一个数组,所以要用progesss[0]来取值
		// 第n个参数就用progress[n]来取值

		if (progress != null) {
			if (progress[0] == -1) {
				downloadProgressDialog.setProgress(100);
			} else if (progress[0] > 0) {
				int percent = progress[0] * 100 / progress[1];
				downloadProgressDialog.setProgress(percent);
			}

		}
		super.onProgressUpdate(progress);
	}

	private String getViewText(Integer progres) {

		if (progres < 1024)
			return progres + "B";
		else
			return progres / 1024 + "KB";
	}

	@Override
	protected void onPostExecute(Integer result) {
		// doInBackground返回时触发，换句话说，就是doInBackground执行完后触发
		// 这里的result就是上面doInBackground执行后的返回值，所以这里是"执行完毕"

		if (handler == null) // 界面可能已经关闭。
			return;
		
		String message = null;
		switch (result) {
		case DOWNLOAD_COMPLETED:
			message = "下载完成";
			break;
		case DOWNLOAD_ERROR:
			message = "下载失败";
			break;
		case DOWNLOAD_CANCELED:
			message = "下载被取消";
			break;
		case UN_AUTHORIZE:
			break;
		}
		if (message != null) {
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
		}
		handler.sendEmptyMessage(1);
		downloadProgressDialog.dismiss();
	}

	@Override
	protected Integer doInBackground(List<String>... params) {
		publishProgress(0);
		HttpPost httpRequest = getHttpPost(UrlConstant.LOCAL_URI+UrlConstant.DOWNLOADCONTACTS);

		List<NameValuePair> paramsUrl = new ArrayList<NameValuePair>();

		paramsUrl.add(new BasicNameValuePair("company_code", ""));
		paramsUrl.add(new BasicNameValuePair("download_type", ""));
		paramsUrl.add(new BasicNameValuePair("dept_values", ""));
		LoginConfig	log =LoginConfigUtil.getConfig(context);
		paramsUrl.add(new BasicNameValuePair("user_phone",log==null?"":log.getUsername()));
		String resonsContent = null;
		try {
			// 发出HTTP request
			httpRequest.setEntity(new UrlEncodedFormEntity(paramsUrl,
					HTTP.UTF_8));
			// 取得HTTP response
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);
			// 若状态码为200 ok

			if (httpResponse.getStatusLine().getStatusCode() == 401) {
			} else if (httpResponse.getStatusLine().getStatusCode() != 200) {
			}
			Header[] headers = httpResponse.getHeaders("Content-Encoding");
			// 取出响应字符串
			resonsContent = getContentBytes2(httpResponse);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("xxxx", e.getMessage());
		}

		return DOWNLOAD_COMPLETED;
	}
	 String inputStream2String(InputStream is) throws IOException {
	        BufferedReader in = new BufferedReader(new InputStreamReader(is, "utf-8"));
	        StringBuffer buffer = new StringBuffer();
	        String line = "";
	        while ((line = in.readLine()) != null) {
	            buffer.append(line);
	        }
	        return buffer.toString();
	    }
	private String getContentBytes2(HttpResponse httpResponse)
			throws IOException, BufferException {
//		InputStream inputStream = httpResponse.getEntity().getContent();
//		HttpEntity entity = httpResponse.getEntity();
//		long length = entity.getContentLength();
//		if (length <= 0)
//			length = 400000;
//		byte[] buf = new byte[1024];
//
//		ByteBuffer byteBuffer = new ByteBuffer(1024 * 1024);
//		int ch;
//		int count = 0;
//		while (((ch = inputStream.read(buf)) != -1)) {
//			if (count + ch > length)
//				length = length + ch;
//			count += ch;
//			byteBuffer.write(buf, ch);
//			publishProgress(count, 2 * (int) length);
//		}
		try {
//			publishProgress(100,0);
			
//			GZIPInputStream g = new GZIPInputStream(new ByteArrayInputStream(
//					byteBuffer.toBytes()));
			
//			InputStream is = new ByteArrayInputStream(byteBuffer.toBytes());
//			GZIPInputStream g = new GZIPInputStream(inputStream);
//			String responseContent =inputStream2String(is);
			String responseContent  = EntityUtils.toString(httpResponse.getEntity());
//			String responseContent =inputStream2String(inputStream);
//			String responseContent = GZIPToString(g);
			
			JSONObject jsonObject = new JSONObject(responseContent);
			JSONArray groupss = (JSONArray) jsonObject.get("groups");
			JSONArray contacts = jsonObject.getJSONArray("contacts");
			String contactGroupVersion = jsonObject.getString("contactGroupVersion");
			
			
			int pageSize = getTotalPage(groupss.length()+contacts.length(),2000);
			//进度条每次添加好多数据
			int pageCount = 50/(pageSize);
			flag = true;
			ContactUserServiceImpl userService = new ContactUserServiceImpl(
					this.context);
			userService.gzipAddGroup(groupss,insertSize,pageCount,downloadProgressDialog);
			Thread.sleep(2000);
			userService.gzipAddContacts(contacts,insertSize,pageCount,downloadProgressDialog);
			SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.context);
			Editor editor = sharedPreferences.edit();
			editor.putString("contactGroupVersion", contactGroupVersion);
		    editor.commit();
//		    ContactUserServiceImpl c = new ContactUserServiceImpl(context);
//            c.initName();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	private int getTotalPage(int total,int limit) {
		if(limit == 0)
			return 1;		
		return (total % limit == 0) ? (total / limit) : (total /limit + 1);
	}
	private String GZIPToString(GZIPInputStream inputstream) {
		BufferedInputStream bis = new BufferedInputStream(inputstream);
		byte[] byteArray = new byte[1024];
		StringBuffer sb = new StringBuffer();
		int tmp = 0;
		int count = 0;
		try {
			while ((tmp = bis.read(byteArray)) != -1) {
				sb.append(new String(byteArray, 0, tmp));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sb.toString();
	}

	private HttpPost getHttpPost(String url) {
		// 建立HTTP Post联机
		HttpPost httpRequest = new HttpPost(url);
		return httpRequest;
	}

}
